<template>
	<view class="container bg-white" :class="'wp-'+platform">
		<view class="status_bar" v-if="platform!='h5'"></view>
		<view class="closebar text-right padding-lr margin-top">
			<view class="text-black text-bold text-xxl" @click="doback"><text class="cuIcon-close"></text></view>
		</view>
		<view class="padding padding-top-xs">
			<view class="text-black text-xxxl">您好,</view>
			<view class="text-lg padding-top-sm text-bold text-black" v-if="action=='login'">欢迎登录{{systemname}}<text v-if="data.register">,<text class="text-blue padding-left-xs" @click="doregister()">立即注册</text></text></view>
			<view class="text-lg padding-top-sm text-bold text-black" v-else>欢迎注册{{systemname}}账户,<text class="text-blue padding-left-xs" @click="dologin()">已有账号？请登录</text></view>
		</view>
		<view class="padding margin-top">
			<form v-if="action=='register'">
				<view class="flex-direction flex cu-form-group">
					<view class="text-black text-boldm text-lg">手机号/邮箱</view>
					<view class="padding-top-sm flex">
						<input :focus="inputfocus=='registerusername'?true:false" class="text-xl lg" type="text" v-model="registerdata.username" placeholder="请输入您的手机号/邮箱" />
						<view @click="registerdata.username=''" v-if="registerdata.username!=''" class="text-xl">
							<text class='cuIcon-roundclosefill text-orange'></text>
						</view>
					</view>
				</view>
				<view class="flex-direction flex cu-form-group margin-top-sm" v-if="data.verifycode">
					<view class="text-black text-boldm text-lg padding-top">验证码</view>
					<view class="padding-top-sm flex">
						<input class="text-xl lg" type="text" v-model="registerdata.verifycode" placeholder="请输入您收到的验证码" />
						<view>
							<button @click="sendcode('register')" class="cu-btn round" :class="verifycodetext.register=='获取验证码'?'bg-yellow':''" :disabled="verifycodetext.register=='获取验证码'?false:true">{{verifycodetext.register}}</button>
						</view>
					</view>
				</view>
				<view class="flex-direction flex cu-form-group margin-top-sm">
					<view class="text-black text-boldm text-lg padding-top">登录密码</view>
					<view class="padding-top-sm flex">
						<input class="text-xl lg" type="text" :password="!viewpassword" v-model="registerdata.password" placeholder="请设置一个登录密码" />
						<view @click="viewpassword=!viewpassword" class="viewpassword">
							<image mode="aspectFit" :src="'/static/images/bg_pwd_'+(viewpassword?'open':'close')+'.png'" class="png"></image>
						</view>
					</view>
				</view>
				<view class="flex-direction flex cu-form-group margin-top-sm">
					<view class="text-black text-boldm text-lg padding-top">昵称</view>
					<view class="padding-top-sm flex">
						<input class="text-xl lg" type="text" v-model="registerdata.nickname" placeholder="设置一个好听的昵称" />
						<view @click="registerdata.nickname=''" v-if="registerdata.nickname!=''" class="text-xl">
							<text class='cuIcon-roundclosefill text-orange'></text>
						</view>
					</view>
				</view>
				<view class="padding-top padding-bottom flex flex-direction margin-top">
					<button @click="registersubmit" class="cu-btn bg-gradual-yellow round lg text-xl">立即注册</button>
				</view>
			</form>
			<form v-else>
				<view class="flex-direction flex cu-form-group">
					<view class="text-black text-boldm text-lg">{{data.loginmethod}}</view>
					<view class="padding-top-sm flex">
						<input :focus="inputfocus=='loginusername'?true:false" class="text-xl lg" type="text" v-model="logindata.username" :placeholder="'请输入您的'+data.loginmethod" />
						<view @click="logindata.username=''" v-if="logindata.username!=''" class="text-xl">
							<text class='cuIcon-roundclosefill text-orange'></text>
						</view>
					</view>
				</view>
				<view class="flex-direction flex cu-form-group margin-top-sm" v-if="logindata.mode=='password'">
					<view class="text-black text-boldm text-lg padding-top">登录密码</view>
					<view class="padding-top-sm flex">
						<input class="text-xl lg" type="text" :password="!viewpassword" v-model="logindata.password" placeholder="请输入您的登录密码" />
						<view @click="viewpassword=!viewpassword" class="viewpassword">
							<image mode="aspectFit" :src="'/static/images/bg_pwd_'+(viewpassword?'open':'close')+'.png'" class="png"></image>
						</view>
					</view>
				</view>
				<view class="flex-direction flex cu-form-group margin-top-sm" v-if="logindata.mode=='code' && data.verifycode">
					<view class="text-black text-boldm text-lg padding-top">验证码</view>
					<view class="padding-top-sm flex">
						<input class="text-xl lg" type="text" v-model="logindata.verifycode" placeholder="请输入您收到的验证码" />
						<view>
							<button :disabled="verifycodetext.login=='获取验证码'?false:true" :class="verifycodetext.login=='获取验证码'?'bg-yellow':''" class="cu-btn round" @click="sendcode('login')">{{verifycodetext.login}}</button>
						</view>
					</view>
				</view>
				<view class="padding-top flex flex-direction margin-top">
					<button class="cu-btn bg-gradual-yellow round lg text-xl" @click="loginsubmit">登s录</button>
				</view>
				<view class="padding text-center text-yellow text-lg margin-top-sm">
					<text v-if="logindata.mode=='password' && data.verifycode" @click="logindata.mode='code'">验证码登录</text>
					<text v-if="logindata.mode=='code'" @click="logindata.mode='password'">密码登录</text>
				</view>
			</form>
			<view class="text-center padding-top-xl margin-top-xl padding-left padding-right" v-if="quicklogin">
				<view class="text-gray text-lg">使用第三方授权登录</view>
				<view class="flex quicklogin padding-left padding-right">
					<view class="flex-sub quick-item" v-if="quicklogins.weixin&&platform=='wxapp'">
						<button class="quick-weixin nobg noaf padding-0" open-type="getUserInfo" @getuserinfo="WxappLogin" withCredentials="true">
							<image mode="aspectFit" class="png" src="@/static/images/icon/auth_weixin.png"></image>
						</button>
					</view>
					<view class="flex-sub quick-item" v-if="inwechat&&platform=='h5'" @click="h5login">
						<view class="quick-weixin">
							<image mode="aspectFit" class="png" src="@/static/images/icon/auth_weixin.png"></image>
						</view>
					</view>
					<view class="flex-sub quick-item" v-if="quicklogins.weixin&&platform!='wxapp'" @click="login('weixin')">
						<view class="quick-weixin">
							<image mode="aspectFit" class="png" src="@/static/images/icon/auth_weixin.png"></image>
						</view>
					</view>
					<view class="flex-sub quick-item" v-if="quicklogins.qq" @click="login('qq')">
						<view class="quick-qq">
							<image mode="aspectFit" class="png" src="@/static/images/icon/auth_qqconnect.png"></image>
						</view>
					</view>
					<view class="flex-sub quick-item" v-if="quicklogins.sinaweibo" @click="login('sina')">
						<view class="quick-sina">
							<image mode="aspectFit" class="png" src="@/static/images/icon/auth_sina.png"></image>
						</view>
					</view>
				</view>
			</view>
			<view class="padding-top text-center text-lg padding-top-xl margin-top-xl">
				<text class="text-gray">{{action=='register'?'注册':'登录'}}即表示同意</text>
				<text class="text-red" @click="showmodal='agreement'">《{{systemname}}用户服务协议》</text>
			</view>
			<view class="cu-modal" :class="showmodal=='agreement'?'show':''">
				<view class="cu-dialog">
					<view class="cu-bar bg-white justify-end">
						<view class="content">{{systemname}}用户服务协议</view>
						<view class="action" @tap="showmodal=''">
							<text class="cuIcon-close text-red"></text>
						</view>
					</view>
					<view class="padding">
						<scroll-view scroll-y class="agreement-text">
							<rich-text :nodes="data.agreement" :selectable="true"></rich-text>
						</scroll-view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {mapState} from 'vuex'
	import core from "@/static/core.js"
	var regmobile = /^(\+)?(86)?0?1\d{10}$/;
	var regmail = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
	var codeInterval = null;
	
	export default {
		computed: mapState(['userId', 'hasLogin']),
		data() {
			return {
				action:"login",
				forwardurl:'',
				fromuid:0,
				inwechat:false,
				viewpassword:false,
				inputfocus:'',
				systemname:"在线教育平台",
				showmodal:'',
				wxappcode:'',
				quicklogin:false,
				quicklogins:{
					"weixin":false,
					"qq":false,
					"sinaweibo":false
				},
				platform:'h5',
				verifycodetext:{
					"login":"获取验证码",
					"register":"获取验证码"
				},
				logindata:{
					mode:"password",
					username:"",
					password:"",
					verifycode:""
				},
				registerdata:{
					username:"",
					password:"",
					verifycode:"",
					nickname:""
				},
				data:{
					title:"登录",
					loginmethod:"手机号/邮箱",
					agreement:"",
					register:1,
					verifycode:1,
					member:{
						uid:0
					}
				}
			}
		},
		onLoad(options) {
			this.platform = core.platform;
			this.systemname = core.system.name;
			this.action = typeof(options.act)=='undefined' ? 'login' : options.act;
			this.fromuid = core.agentid;
			this.inwechat = core.inwechat;
			if(this.inwechat) this.quicklogin = true;
			if(typeof(options.forward)!='undefined'){
				this.forwardurl = options.forward;
			}
			var that = this;
			this.initData('auth',{},function(res){
				console.log(res)
				if(res.member.uid>0){
					core.login(res.member);
					let redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
					return core.toast('登录成功', redirecturl ,'success');
				}
				if(that.action=='register'){
					if(res.register==0){
						core.toast('暂未开放注册');
					}else{
						this.doregister();
					}
				}
			});
			if(this.platform!='h5'){
				uni.getProvider({
				    service: 'oauth',
				    success: function (res) {
						if (res.provider && res.provider.length) that.quicklogin = true;
				        for(var p in res.provider){
							that.quicklogins[res.provider[p]] = true;
						}
				    }
				});
			}
		},
		onShow() {
		},
		methods:{
			initData(route, data={}, callback=false){
				var that = this;
				core.get(route,function(res){
					if(typeof(res.message)!='undefined' && typeof(res.type)!='undefined'){
						return core.report(res);
					}
					// that.data = res;
					console.log(res)
					uni.setNavigationBarTitle({
						title:res.title
					});
					if(callback){
						callback(res);
					}
				},data);
			},
			naviTo(page,data={}){
				return core.navito(page,data);
			},
			h5login(){
				if(this.platform!='h5') return false;
				let h5url = core.url('','app');
				window.location.href = h5url;
			},
			doregister(){
				this.action = 'register';
				uni.setNavigationBarTitle({
					title:'注册'
				})
			},
			dologin(){
				this.action = 'login';
				uni.setNavigationBarTitle({
					title:'登录'
				})
			},
			doback(){
				return core.back();
			},
			login(provider){
				if(!this.quicklogins[provider]) return core.toast('暂不支持该登录方式');
				var that = this;
				uni.login({
					provider: provider,
					success: (res) => {
						uni.getUserInfo({
							provider: provider,
							lang:'zh_CN',
							success: (infoRes) => {
								/**
								 * 实际开发中，获取用户信息后，需要将信息上报至服务端。
								 * 服务端可以用 userInfo.openId 作为用户的唯一标识新增或绑定用户信息。
								 */
								//this.toMain(infoRes.userInfo.nickName);
								//console.log(infoRes.userInfo);
								let _provider = this.platform=='wxapp' ? 'wxapp' : provider;
								let postdata = {provider:_provider,userinfo:infoRes.userInfo}
								if(_provider=='wxapp'){
									postdata.code = res.code;
								}
								if(this.fromuid>0) postdata.fromuid = this.fromuid;
								postdata.appsecret = core.apitoken;
								return core.post('auth/quicklogin',function(res){
									if(res.type!='success') return core.report(res);
									core.login(res.member);
									let redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
									core.toast(res.message, redirecturl ,'success');
								},postdata);
							},
							fail() {
								if(provider=='weixin' && that.platform=='wxapp'){
									that.wxappcode = res.code;
									return that.showmodal = 'wxapplogin';
								}
								return core.toast('登陆失败，请重试');
							}
						});
					},
					fail: (err) => {
						core.toast('授权登录失败');
						console.error('授权登录失败：' + JSON.stringify(err));
					}
				});
			},
			WxappLogin(e){
				this.showmodal = '';
				var that = this;
				if(this.wxappcode==''){
					return uni.login({
						provider: 'weixin',
						success: (res) => {
							that.wxappcode = res.code;
							that.WxappLogin();
						},
						fail: (err) => {
							core.toast('授权登录失败');
							console.error('授权登录失败：' + JSON.stringify(err));
						}
					});
				}
				uni.getUserInfo({
					provider: 'weixin',
					lang:'zh_CN',
					success: (infoRes) => {
						console.log(infoRes.userInfo);
						return core.post('auth/quicklogin',function(res){
							if(res.type!='success') return core.report(res);
							core.login(res.member);
							let redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
							core.toast(res.message, redirecturl ,'success');
						},{provider:'wxapp','code':that.wxappcode,userinfo:infoRes.userInfo,appsecret:core.apitoken});
					},
					fail(e) {
						core.toast('登陆失败');
					}
				});
			},
			async sendcode(sendfrom='login'){
				if(this.verifycodetext[sendfrom]!='获取验证码') return false;
				var username = sendfrom=='login' ? this.logindata.username : this.registerdata.username;
				if(username==''){
					this.inputfocus = sendfrom+'username';
					return core.toast('请输入您的手机号或邮箱');
				}
				if (!username.match(regmobile) && !username.match(regmail)) {
					this.inputfocus = sendfrom+'username';
					return core.toast('手机号或邮箱格式不正确');
				}
				console.log(username)
				var that = this;
				(await this.$api.reqPost({
					url:"user/phone",
					data:{phone:username}
				}).then(res=>{
					if(res.code==200){
						console.log(res)
							core.toast(res.msg,'','success');
							that.verifycodetext[sendfrom] = '120s';
							var n = 120;
							/**
							 * 好像时倒计时函数
							 */
							codeInterval = setInterval(function(){
								if(n==0){
									clearInterval(codeInterval);
									that.verifycodetext[sendfrom] = '获取验证码';
									return;
								}else{
									that.verifycodetext[sendfrom] = n+'s';
								}
								n--
							},1e3);
					}else if(res.code==4003){
						core.toast(res.msg,'','s');
					}
				}))
				// return core.get('util/code',function(res){
				// 	if(res.type!='success') return core.report(res);
				// 	core.toast(res.message,'','success');
				// 	that.verifycodetext[sendfrom] = '120s';
				// 	var n = 120;
				// 	codeInterval = setInterval(function(){
				// 		if(n==0){
				// 			clearInterval(codeInterval);
				// 			that.verifycodetext[sendfrom] = '获取验证码';
				// 			return;
				// 		}else{
				// 			that.verifycodetext[sendfrom] = n+'s';
				// 		}
				// 		n--
				// 	},1e3);
				// },{from:sendfrom,username:username});
			},
			async loginsubmit(){
				let postdata = this.logindata;
				if(postdata.username=='') return core.toast('用户名不能为空');
				if(postdata.mode=='password' && postdata.password=='') return core.toast('登录密码不能为空');
				if(postdata.mode=='code' && postdata.verifycode=='' && this.data.verifycode) return core.toast('验证码不能为空');
				if(this.fromuid>0) postdata.fromuid = this.fromuid;
				postdata.appsecret = core.apitoken;
				// postdata.uId=postdata.username;
				var that = this;
				// return core.post('auth/login',function(res){
				// 	if(res.type!='success') return core.report(res);
				// 	core.login(res.member);
				// 	var redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
				// 	core.toast(res.message, redirecturl ,'success');
				// },postdata,'json',true);
				console.log(postdata)
				var res=(await this.$api.reqPost({
					url:"user/login",
					data:postdata,
				}));
				if(res.code==200){
					console.log(res.data)
					core.login(res.data)
					var redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
					core.toast('登录成功', redirecturl ,'success');
				}else{
					core.toast('用户名和密码错误');
				}
			},
			 registersubmit(){
				let postdata = this.registerdata;
				if(postdata.username=='') return core.toast('用户名不能为空');
				if(postdata.password=='') return core.toast('登录密码不能为空');
				if(postdata.verifycode=='' && this.data.verifycode) return core.toast('验证码不能为空');
				if(postdata.nickname=='') return core.toast('请设置一个昵称');
				if (!postdata.username.match(regmobile) && !postdata.username.match(regmail)) {
					return core.toast('手机号或邮箱格式不正确');
				}
				if(this.fromuid>0) postdata.fromuid = this.fromuid;
				postdata.appsecret = core.apitoken;
				var that = this;
				console.log(postdata);
				(this.$api.reqPost({
					url:"user/register",
					data:postdata,
				}).then(res=>{
					console.log(res)
					if(res.code==200){
						console.log(res)
						
						 // core.login(postdata);
						// var redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
						core.toast('注册成功', 'login' ,'success');
					}else{
						core.toast("验证码错误");
					}
				}))
				// return core.post('auth/register',function(res){
				// 	if(res.type!='success') return core.report(res);
				// 	core.login(res.member);
				// 	var redirecturl = that.forwardurl=='' ? 'home' : that.forwardurl;
				// 	core.toast(res.message, redirecturl ,'success');
				// },postdata,'json', true);
			}
		}
	}
</script>

<style>
.container{min-height: 100vh;}
.wp-wxapp .closebar{margin-right: 200upx;}
.agreement-text{max-height: 40vh; font-size: 32upx; line-height: 50upx; text-indent: 64upx; text-align: left;}
.cu-form-group input.text-xl{font-size: 120%;}
.viewpassword .png{width: 1.2rem; height: 100%;}
.cu-btn.text-xl{font-size: 18px;}
.quick-item{padding-top: 30upx;}
.quick-item .png{width: 100upx; height: 100upx;}
</style>
